package com.efun.center.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
@Order(1)
public class LogInterceptor {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Around("@within(org.springframework.web.bind.annotation.RequestMapping)")
    public Object doLog(ProceedingJoinPoint joinPoint) {
        long startTime = System.currentTimeMillis();

        Thread.currentThread().setName("CT-" + joinPoint.getSignature().getName() + "-" + startTime);

        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attrs.getRequest();
        String uri = request.getRequestURI();
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entrys : parameterMap.entrySet()) {
            String value = "";
            String[] values = entrys.getValue();
            for (String val : values) {
                value += val + ",";
            }
            if (values.length > 0) {
                value = value.substring(0, value.length() - 1);
            }
            params.put(entrys.getKey(), value);
        }

        logger.info("START -- uri: {}, params: {}", uri, params);

        Object result = null;
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }

        logger.info("END -- uri: {}, excTime: {}", uri, System.currentTimeMillis() - startTime);

        return result;
    }

}
